/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package p2p.raca.Client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author p
 */
public class ClientListener extends Thread {
    private ServerSocket waitComSocket = null;
    private String conteudo;
    private String clientName;
    private int size;
    
    
    
    public ClientListener()
    {}
    
    
      public void openCom()
    { Socket connection = null;
        try {   
            
         waitComSocket = new ServerSocket(5056);  
         //wait until a client attempts to connect  
         connection = waitComSocket.accept();

         clientName = waitComSocket.getInetAddress().getHostName();
         //get an InputStream from the socket  
         DataInputStream fromClient = new DataInputStream(connection.getInputStream());
         DataOutputStream toClient = new DataOutputStream(connection.getOutputStream());
         
         byte buffer[] = new byte[1024];  
         fromClient.read(buffer); 
         conteudo = new String(buffer).trim();

            
         if (conteudo.substring(0,8).contains("donwload"))
         {
            File file = new File ("shared/"+conteudo.substring(8,conteudo.length())+".txt");
            toClient.write((int)file.length());
            
         }
         connection.close();
         waitComSocket.close();
      } catch (Exception e) {  
            try {
                connection.close();
            } catch (IOException ex) {
                        }
            try {
                waitComSocket.close();
            } catch (IOException ex) {
            }
      } 
 
    }
    
    
    @Override
    public void run()
    {
        while (true)
        {
            openCom();
            ClientFileSender CFS = new ClientFileSender("shared/"+conteudo.substring(8,conteudo.length())+".txt");
            CFS.start();
        }
    }
    
}
